import { movieSubjectDetailUsingGET } from '@/services/otherworldly-station-backend/DoubanController';
import {
    deleteFilmTelevisionUsingPOST,
    updateFilmTelevisionUsingPOST,
} from '@/services/otherworldly-station-backend/FilmTelevisionController';
import { ProCard } from '@ant-design/pro-components';
import { Card, Divider, Image, List, message, Modal, Pagination, Spin, Tag } from 'antd';
import React, { CSSProperties, useState } from 'react';
import styles from './index.less';

export type Props = {
    records: API.DoubanSearchMovieVO[];
    recordsCount: number;
    setCurrentPage: (page: number) => void;
    loadData: (start: number, count: number) => Promise<void>;
};
const iconStyles: CSSProperties = {
    color: 'rgba(0, 0, 0, 0.2)',
    fontSize: '18px',
    verticalAlign: 'middle',
    cursor: 'pointer',
};

const getImages = (_url: string | undefined) => {
    if (_url !== undefined) {
        let _u = _url.substring(7);
        return 'https://images.weserv.nl/?url=' + _u;
    }
};
const GlobalCardList: React.FC<Props> = (props) => {
    const { records, recordsCount, loadData, setCurrentPage } = props;
    const [modalOpen, setModalOpen] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [movieItem, setMovieItem] = useState<API.FilmTelevisionVO>({});
    const [isCompleteLoading, setIsCompleteLoading] = useState<boolean>(false);
    const [isWatched, setIsWatched] = useState<boolean>(false);

    const deleteMyFavorite = (id: number) => {
        // 取消收藏
        setSubmitLoading(true);
        // 取消收藏，删除本地记录
        deleteFilmTelevisionUsingPOST({ id })
            .then(async (res) => {
                if (res.code === 0) {
                    message.warning('影片已从您的影视列表中移除');
                }
            })
            .finally(() => {
                setModalOpen(false);
                setSubmitLoading(false);
            });
    };

    /**
     * 获取影片详情
     * @param id
     */
    const showFilmDetail = (id: number) => {
        setIsWatched(false);
        setIsCompleteLoading(true);
        setMovieItem({});
        // 获取影片详情
        movieSubjectDetailUsingGET({ id })
            .then((res) => {
                if (res.code === 0) {
                    let data = res.data as API.DoubanSearchMovieVO;
                    console.log('showMovieDetail：', data);
                    if (data.watchStatus) {
                        // 有值说明已存入影视列表
                        setIsWatched(true);
                    }
                    setMovieItem(data);
                    setIsCompleteLoading(false);
                    setModalOpen(true);
                }
            })
            .finally(() => {
                setIsCompleteLoading(false);
            });
    };

    /**
     * 根据ID修改观影状态
     *
     * @param value
     */
    const updateFilmWatchStatus = (value: any) => {
        setSubmitLoading(true);
        const body = { ...movieItem, watchStatus: value };
        updateFilmTelevisionUsingPOST(body).then(async (res) => {
            if (res.code !== 0) {
                message.error(res.message);
            } else if (res.code === 0) {
                setModalOpen(false);
                setSubmitLoading(false);
            }
        });
    };

    return (
        records && (
            <>
                <Spin size="large" spinning={submitLoading}>
                    <Modal
                        width="500px"
                        centered
                        open={modalOpen}
                        okText={'删除'}
                        onCancel={() => setModalOpen(false)}
                    >
                        <ProCard
                            direction="column"
                            ghost
                            gutter={{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1, xxl: 2 }}
                            style={{ overflow: 'auto', marginTop: '15px' }}
                            className={styles.coverCardList}
                        >
                            <ProCard style={{ textAlign: 'center' }}>
                                <Image width={200} src={getImages(movieItem.images?.medium)} />
                            </ProCard>
                            <ProCard>
                                <h2>
                                    <b>{movieItem.name}</b>

                                    <span></span>
                                    <span
                                        style={{
                                            marginLeft: '10px',
                                            fontSize: '18px',
                                        }}
                                    >
                                        {movieItem.score ? movieItem.score : 0} 分
                                    </span>
                                </h2>
                                {movieItem.tags?.map((item, index) => {
                                    return index < 6 ? (
                                        <Tag
                                            key={item}
                                            bordered={true}
                                            color="#fa5822"
                                            style={{ marginBottom: '10px' }}
                                        >
                                            {item}
                                        </Tag>
                                    ) : null;
                                })}
                                <Divider style={{ margin: '0 0 10px 0' }} />
                                <div style={{ height: 'auto' }}>{movieItem.description}</div>
                            </ProCard>
                        </ProCard>
                    </Modal>
                </Spin>
                <Spin size="large" spinning={isCompleteLoading}>
                    <List<any>
                        className={styles.coverCardList}
                        rowKey="id"
                        grid={{ gutter: 24, xxl: 8, xl: 6, lg: 4, md: 4, sm: 2, xs: 1 }}
                        dataSource={records}
                        renderItem={(item) => {
                            return (
                                <List.Item>
                                    <Card
                                        className={styles.card}
                                        hoverable
                                        cover={
                                            <img
                                                alt={item.images?.medium}
                                                src={getImages(item.images.medium)}
                                            />
                                        }
                                        onClick={() => {
                                            showFilmDetail(item.id);
                                        }}
                                    >
                                        <Card.Meta
                                            title={<a>{item.title}</a>}
                                            description={item.airWeekday}
                                        />
                                        <div className={styles.cardItemContent}>
                                            <span>{item.year + ' 上映'}</span>
                                            <div
                                                style={{
                                                    color: 'rgba(0, 0, 0, 0.6)',
                                                }}
                                            ></div>
                                        </div>
                                    </Card>
                                </List.Item>
                            );
                        }}
                    />
                    {recordsCount > 20 ? (
                        <Pagination
                            style={{ textAlign: 'center' }}
                            simple
                            defaultCurrent={1}
                            defaultPageSize={20}
                            total={recordsCount}
                            onChange={async (page, pageSize) => {
                                await loadData(page - 1, pageSize);
                                setCurrentPage(page);
                                window.scrollTo({
                                    top: 0,
                                    behavior: 'smooth',
                                });
                            }}
                        />
                    ) : null}
                </Spin>
            </>
        )
    );
};

export default GlobalCardList;
